<!--数据回显-->
<!--1.提交数据报错后,将刚才提交的数据回显到表单中-->
<!--2.编辑数据的时候,取消编辑还原旧数据-->

<template>
  <section>

    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyWords" placeholder="角色名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="find">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd()">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>


    <!--列表-->
    <el-table :data="pageInfo" highlight-current-row  @selection-change="selChange" style="width: 100%;">
      <!--      选框-->
      <el-table-column type="selection" width="55">
      </el-table-column>

      <el-table-column type="index" width="60">
      </el-table-column>

      <!--      列表-->
      <!--      :formatter="formatStatus"-->

      <el-table-column prop="name" label="角色名字" :span="6" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="编码描述" :span="6" sortable>
      </el-table-column>
      <el-table-column label="操作" :span="8">

        <template v-slot="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--批删和分页-->
    <!--    page-size:每页显示条目个数-->
    <!--    page-sizes:每页显示个数选项器-->
    <!--    :disabled="this.sels.length === 0" 如果没有数据让删除按钮失效 -->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemoveRole" :disabled="this.sel.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          layout="total, sizes,prev, pager, next,jumper"
          @current-change="handleCurrentChange"

          :page-size="query.pageSize"
          :page-sizes="[5,10,15,20,30]"
          :total="pageInfo.total"
          :current-page="query.currentPage"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--****************************************************************************-->
    <!--*****************************新增和编辑界面***********************************-->
    <!--****************************************************************************-->
    <!--
    :visible.sync  控制dialog是否显示
     :rules  绑定表单校验规则
     prop:绑定校验规则的名称
   -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px"  ref="su"><!-- ref给表单取别名 -->
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="编码描述">
          <el-input v-model="saveForm.sn"></el-input>
        </el-form-item>
        <el-form-item label="权限" >
          <el-tree :data="permissionTree"
                   accordion
                   node-key="id"
                   ref="tree"
          :props="defaultProps" show-checkbox>


          </el-tree>
        </el-form-item>

      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
    <!--****************************************************************************-->
    <!--****************************************************************************-->
    <!--****************************************************************************-->

  </section>
</template>

<script>
import {batchRemoveDep, removeDep, getDepList, addDep, findEmployees, DepTree} from "../../api/api";
import permission from "./Permission.vue";

export default {
  name: "Permission",
  computed: {
    permission() {
      return permission
    }
  },
  // data为初始化页面值
  data() {
    return {
      defaultProps: {
        //下一级是什么
        children: 'children',
        //用来展示的label的是什么
        label: 'name'
      },


      pageInfo: {
        // 总条数
        total: 0,
        rows: []
      },

      //初始化分页
      query: {
        //当前页码
        currentPage: 1,
        //每页显示条数
        pageSize: 10
      },
      /***************************************/

      //高级查询名字
      filters: {
        keyWords: ''
      },

      sel: [],//列表选中列，批删

      /***************************************************************/
      /******************初始化新增和编辑方法****************************/
      /***************************************************************/
      saveFormVisible: false,//新增界面是否显示
      saveLoading: false,
      options: [],
      title: "新增或修改角色",
      // 表单校验规则
      //trigger:blur---失去焦点时触发验证
      saveFormRules: {
        name: [
          {required: true, message: '请输入角色名字', trigger: 'blur'}
        ]
      },
//新增界面数据
      saveForm: {
        id:'',
        name: '',
        sn:'',
      },


      permissionTree: [],

      // 显示新增
      //显示新增界面
      handleAdd() {
        this.saveFormVisible = true
        this.saveForm = {
          id:null,
          name: '',
          sn: '',
        }
        this.$refs.tree.setCheckedKeys([])
        this.permissionTree()
      },

      //显示编辑界面,需要做数据回显
      //把row行中的数据拷贝到表单中去
      handleEdit(index, row) {
        Object.assign(this.saveForm, row)
        this.saveFormVisible = true;

        this.loadPermissionIdByRoleId(row.id)
      },

      /**************************************************************/
      /*****************************删除*********************************/
      /**************************************************************/
      //index:当前数据的行号
      //row:当前行数据
      handleDel(index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          //NProgress.start();
          let para = row.id
          this.$http.delete("/role/"+para).then((res) => {
            this.listLoading = false
            //NProgress.done();
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getPermission()
          });
        }).catch(() => {

        });
      },


      // **************************************************//
      // *********************批删*************************//
      // **************************************************//


      //批量删除
      batchRemoveRole() {
        //箭头函数相当于function函数简写
        //去掉function,改成箭头=>
        //形参小括号写到箭头左边
        //记住要去掉.toString
        var ids = this.sel.map(item => item.id)
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          //NProgress.start();

          this.$http.patch("/role",{ids:ids}).then((res) => {

            this.listLoading = false;
            //NProgress.done();
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getPermission()
          });
        }).catch(() => {

        });
      }
      // **************************************************
      // **************************************************
      // **************************************************
    }
  },


  methods: {
    loadPermissionIdByRoleId(id){
      this.$http.get("/role/permission/"+id).then((res) => {
        this.$refs.tree.setCheckedKeys(res.data.data);
      })
    },

    //列表更改
    selChange(sel) {
      this.sel = sel
    },


    //提交弹出框
    //$refs代表所有ref:取了别名的
    saveSubmit() {
      this.$refs.su.validate((valid) => {
        if (valid) {
          this.$confirm('确定提交么?', '提示', {}).then(() => {
            this.saveLoading = true
            let NewSaveForm = {
                  role:this.saveForm,
                  permissionIds:this.$refs.tree.getCheckedKeys()
                }
            this.$http.put("/role/addOrUpdate",NewSaveForm).then((res) => {
              if (res.data.success) {
                this.$message({
                  message: '成功',
                  type: 'success'
                })
              } else {
                this.$message.error(res.data.message)
              }
              this.getPermission()
              this.saveLoading = false
              this.saveFormVisible = false
            })
          })
        }
      })
    },


    find() {
      this.query.currentPage = 1
      this.getPermission()
    },

    //js方法
    //账号状态转换
    // formatStatus: function (row, column) {
    // 	return row.state == 1 ? '正常' : row.state == 0 ? '停用' : '未知';
    // },

    //当前页码改变时触发
    handleCurrentChange(currentPage) {
      this.query.currentPage = currentPage
      this.getPermission()
    },

    //页码大小改变时触发(success)
    handleSizeChange(pageSize) {
      this.query.pageSize = pageSize
      this.getPermission()
    },

    //获取角色列表
    getPermission() {
      this.listLoading = true
      //封装数据
      let query = {
        //this调用的是data里面的初始化数据
        currentPage: this.query.currentPage,
        pageSize: this.query.pageSize,
        keyWord: this.filters.keyWord
      }

      // this.$http.post("/dept",query)
      this.$http.post("/role",{query:query}).then(res=>{

        //res.data.data返回数据需要嵌套一层
        res = res.data
        this.pageInfo = res.data.data

        // 总数
        this.pageInfo.total = res.data.count
        //关闭加载
        this.listLoading = false
      }).catch(result => {
        this.$message({message: '分页查询失败', type: 'error'});
      })
    },

    //下拉框
    // loadEmployees() {
    //   findEmployees().then((res) => {
    //     this.options = res.data
    //
    //   })
    // },
    //角色树
    loadPermissionTree(){
      this.$http.get("/permission/tree").then(res=>{
        this.permissionTree = res.data.data
      })
    }


  },
  //页面加载时
  //要注意mounted位置
  mounted() {
    this.getPermission()
    this.loadPermissionTree()
  }
}
</script>

<style scoped>

</style>